package com.example.ui.register;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.huashangapp.R;
import com.example.net.AnalyzingJson;
import com.example.net.NetRequest;
import com.example.ui.register.util.City;
import com.example.ui.register.util.SelectCityAdapter;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

@SuppressLint("HandlerLeak")
public class SelectCity extends Fragment {
	private String father;
	private ListView sc_lv;

	private ArrayList<City> sc_list;
	private SelectCityAdapter sc_adapter;
	private String data;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {				
		father = RegisterActivity4.provinceID;
		final View v = inflater.inflate(R.layout.a_selectcity, null);
		new Thread(sp_run).start();
		sc_list = new ArrayList<City>();
		sc_adapter = new SelectCityAdapter(getActivity(), sc_list);
		sc_lv = (ListView) v.findViewById(R.id.as_clist);

		sc_lv.setAdapter(sc_adapter);
		sc_lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				
				RegisterActivity4.city = sc_list.get(position).getCity();
				getActivity().finish();
				RegisterActivity4.h.sendEmptyMessage(0);
			}
		});
		return v;
	}

	private Handler h = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				sc_adapter.setCcInfos(sc_list);
				sc_adapter.notifyDataSetChanged();
				break;
			case 2:
				
				break;

			default:
				break;
			}

		};

	};
	Runnable sp_run = new Runnable() {

		@Override
		public void run() {
			data = NetRequest.postRequestCity(father);
			try {
				JSONObject jo = new JSONObject(data);
				String result = jo.getString("response");
				if (result.equals("true")) {
					sc_list = AnalyzingJson.getcontent_City(data);
					h.sendEmptyMessage(1);
				} else {
					h.sendEmptyMessage(2);
				}
			} catch (JSONException e) {
				
				e.printStackTrace();
			}

		}
	};

}
